package joq.server;

import java.util.NoSuchElementException;
import java.util.Scanner;

public class MessageProtocol
{
    private static final String pattern = "(put|get) (\\S+,?)+ (.*)";

    public static Message decode(String input) throws ProtocolError
    {
	Message msg;
	String[] tags;
	String method, body;
	Scanner s = new Scanner(input);

	s.useDelimiter(" ");

	try {
	    method = s.next("put|get");
	    tags = s.next().split(",");
	    body = (method.equalsIgnoreCase("put")) ? s.nextLine().substring(1) : null;
	} catch (NoSuchElementException e) {
	    throw new ProtocolError();
	} finally {
	    s.close();
	}

	if (method.equalsIgnoreCase("put"))
	    return new Message(body, tags);
	else
	    return new Message(tags);
    }
}
